<?php
include("setup.php");
if((!eregi('i.',$_SERVER['QUERY_STRING'])) and (!eregi('f.',$_SERVER['QUERY_STRING'])) and (!eregi('s.',$_SERVER['QUERY_STRING'])) and (!eregi('m.',$_SERVER['QUERY_STRING'])) and (!eregi('c.',$_SERVER['QUERY_STRING'])) and (!eregi('d.',$_SERVER['QUERY_STRING']))){
	header("HTTP/1.0 404 Not Found");
	exit;
}

session_cache_limiter();
 
include $setupdata['core_dir']."/setup.php";
$setupdata['send_error_to'] = 'bugz@justpageit.lt';
$setupdata['null_binary_path'] = $setupdata['binary_path'];
$setupdata['default_languages'] = strtolower($setupdata['default_languages']);
include $setupdata['core_dir']."/classes/mysql.php";
$mysqlclass = new MysqlClass;
include $setupdata['core_dir']."/classes/images.php";
$imageclass = new ImagesClass;
include $setupdata['core_dir']."/classes/files.php";
$fileclass = new FilesClass;

/**
 * Save image to disk
 *
 * mime is not used. For future.
 * 
 * @param resource $image
 * @param string $mime
 * @param string $path
 */
function save_img($image, $mime, $path)
{
	if( $mime == "image/png" )
    imagepng($image);
  else
    imagejpeg($image, $path, 90);
	chmod ($path, 0666);
}

/**
 * Outputs image
 *
 * mime is not used. For future.
 * 
 * @param resource $image
 * @param string $mime
 */
function output_img($image, $mime)
{
	header("Last-Modified: ".gmdate("D, d M Y H:i:s", time())." GMT");
  header("Content-type: ".$mime);
  if( $mime == "image/png" )
    imagepng($image);
  else
    imagejpeg($image, $path, 90);
  //imagejpeg($image, '', 90);
}

/**
 * Creates image
 * 
 * If is defined imagecreatetruecolor creates truecoloriamge else creates simple image
 * src_im: source image link resource
 * dst_x: x-coordinate of destination point
 * dst_y: y-coordinate of destination point
 * src_x: x-coordinate of source point
 * src_y: y-coordinate of source point
 * dst_w: Destination width
 * dst_h: Destination height
 * src_w: Source width
 * src_h: Source height
 *
 * @param resource $src_image
 * @param int $dst_x
 * @param int $dst_y
 * @param int $src_x
 * @param int $src_y
 * @param int $dst_w
 * @param int $dst_h
 * @param int $src_w
 * @param int $src_h
 * @return resource
 */
function get_resized_img($src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $mime)
{
	$thumb;
	if((function_exists("imagecreatetruecolor")) and (function_exists("imagecopyresampled"))){
		$thumb = imagecreatetruecolor($dst_w, $dst_h);
    
    if( ($mime == "image/gif") || ($mime == "image/png") ) {
      $trnprt_indx = imagecolortransparent($src_image);

      if( $trnprt_indx  >= 0 ) {
        $trnprt_color = imagecolorsforindex($src_image, $trnprt_indx);
        $trnprt_indx = imagecolorallocate($thumb, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
        imagefill($thumb, 0, 0,  $trnprt_indx);
        imagecolortransparent($thumb, $trnprt_indx);
      }
      elseif( $mime == "image/png" ) {
        imagealphablending($thumb, false);
        $color = imagecolorallocatealpha($thumb, 0, 0,  0, 127);
        imagefill($thumb, 0, 0,  $color);
        imagesavealpha($thumb, true);
      }
    }
    
		imagecopyresampled($thumb, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
	} else {
		$thumb = imagecreate($dst_w, $dst_h);
		imagecopyresized($thumb, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
	}
	return $thumb;
}

function get_real_data($id, $type){
	global $setupdata, $imageclass, $mysqlclass;
	$tmp = round($id / 250);
	
	$path_to_cache_file = $setupdata['binary_path']."/ids"."/".$tmp."/".$id;
			
	if (file_exists($path_to_cache_file)) {
		require $path_to_cache_file;
		if (isset($data_id)) {
			$rows['parent'] = $data_id['parent'];
			$data_id = $data_id['info'];
			$rows['link'] = $data_id['name'];
			$rows['size'] = $data_id['size'];
			$rows['mime'] = $data_id['type'];
			return $rows;
		}
	}
	$mysqlclass->connect_db($setupdata['HostName'], $setupdata['UserName'], $setupdata['Password'], $setupdata['DBName']);
	$result = $imageclass->image_get_link($id, $type);
	$mysqlclass->close_db();
	return $result;
}

function paste_watermark($path, $watermark){
	global $setupdata;
	$imagedata = getimagesize($path);
	if ($imagedata[2] == 1) {
		$tmp = ImageCreateFromGif($path); 
		$tmpfname = tempnam("/tmp", "FOO");
		ImageJPEG($tmp, $tmpfname, 90);
		$photoImage = ImageCreateFromJpeg($tmpfname); 
		ImageDestroy($tmp);
		unlink($tmpfname);
	} elseif ($imagedata[2] == 2) $photoImage = ImageCreateFromJpeg($path); 
	
	ImageAlphaBlending($photoImage, true); 
	$logoImage = ImageCreateFromPNG($setupdata['null_binary_path']."/watermark/".$watermark['info']['name']); 
	$logoW = ImageSX($logoImage);
	$logoH = ImageSY($logoImage);

	if ($watermark['x'] == 66.66) {
		$x = (ImageSX($photoImage)/100*$watermark['x'])-(ImageSX($photoImage)/100*16.5)-$logoW/2;		
	} elseif ($watermark['x'] == 100.00) {
		$x = ImageSX($photoImage)-$logoW;
	} else $x = 0;

	if ($watermark['y'] == 66.66) {
		$y = (ImageSY($photoImage)/100*$watermark['y'])-(ImageSY($photoImage)/100*16.5)-$logoH/2;		
	} elseif ($watermark['y'] == 100.00) {
		$y = ImageSY($photoImage)-$logoH;
	} else $y = 0;
	
	ImageCopy($photoImage, $logoImage, $x, $y, 0, 0, $logoW, $logoH);
	header("Last-Modified: ".gmdate("D, d M Y H:i:s", time())." GMT");
	header("Content-type: image/jpeg");
	ImageJPEG($photoImage);
	ImageDestroy($photoImage);
	ImageDestroy($logoImage);
}

function resize($img, $w, $h, $path, $watermark=NULL){
	$imagedata = getimagesize($img);
	if (!isset($imagedata['mime'])){
		if ($imagedata[2] == 1) $imagedata['mime'] = 'image/gif';
		elseif ($imagedata[2] == 2) $imagedata['mime'] = 'image/jpeg';
    elseif ($imagedata[2] == 3) $imagedata['mime'] = 'image/png';
    elseif ($imagedata[2] == 6) $imagedata['mime'] = 'image/bmp';
    
	} 
	if ($imagedata['mime'] == 'image/jpeg')	$image = ImageCreateFromJpeg($img); 
	elseif ($imagedata['mime'] == 'image/gif') $image = ImageCreateFromGif($img);
  elseif ($imagedata['mime'] == 'image/png') $image = imagecreatefrompng($img);
  elseif ($imagedata['mime'] == 'image/bmp') $image = imagecreatefromwbmp($img);
	
	$thumb = get_resized_img($image, 0, 0, 0, 0, $w, $h, $imagedata[0], $imagedata[1], $imagedata['mime']);
	save_img($thumb, $imagedata['mime'], $path);
	if ($watermark==NULL){
		output_img($thumb, $imagedata['mime']);
		
		ImageDestroy($image);
		ImageDestroy($thumb);
	} else {
		paste_watermark($path, $watermark);
	}
}

/**
 * Resise, save and outputs image with cont. dimentions
 *
 * @param resource $img
 * @param int $w
 * @param int $h
 * @param string $position
 * @param string $path
 * @param mixed $watermark
 */
function resize_const($img, $w, $h, $position, $path, $watermark=NULL){
	$imagedata = getimagesize($img);
	$cur_w = $imagedata[0];
	$cur_h = $imagedata[1];
	$cur_ratio = $cur_w / $cur_h; 
	$ratio = $w / $h;
	
	$w_ratio = $cur_w / $w;
	$h_ratio = $cur_h / $h;
	
	//Calculates recuared buff image dimension
	if($w_ratio < $h_ratio){
		$new_w = intval($cur_w / $w_ratio + 0.5);
		$new_h = intval($cur_h / $w_ratio + 0.5);
	}
	else{
		$new_w = intval($cur_w / $h_ratio + 0.5);
		$new_h = intval($cur_h / $h_ratio + 0.5);
	}
	
	//Calculates deltas
	$center_x = intval(( $new_w - $w ) / 2.0);
	$center_y = intval(( $new_h - $h ) / 2.0);
	switch($position){
		case 'nw':
			$x = 0;
			$y = 0;
			break;
		case 'n':
			$x = $center_x;
			$y = 0;
			break;
		case 'ne':
			$x = $new_w - $w;
			$y = 0;
			break;
		case 'w':
			$x = 0;
			$y = $center_y;
			break;
		case 'e':
			$x = $new_w - $w;
			$y = $center_y;
			break;
		case 'sw':
			$x = 0;
			$y = $new_h - $h;
			break;
		case 's':
			$x = $center_x;
			$y = $new_h - $h;
			break;
		case 'se':
			$x = $new_w - $w;
			$y = $new_h - $h;
			break;
		case 'c':
		default:
			$x = $center_x;
			$y = $center_y;
			break;
	}
	
	if ($imagedata['mime'] == 'image/jpeg') $image = ImageCreateFromJpeg($img); 
	elseif ($imagedata['mime'] == 'image/gif') $image = ImageCreateFromGif($img);
  elseif ($imagedata['mime'] == 'image/png') $image = imagecreatefrompng($img);
  elseif ($imagedata['mime'] == 'image/bmp') $image = imagecreatefromwbmp($img);
	$buf_img = get_resized_img($image, 0, 0, 0, 0, $new_w, $new_h, $cur_w, $cur_h);
	$res_img = imagecreatetruecolor($w, $h);
	imagecopy( $res_img, $buf_img, 0, 0, $x, $y, $w, $h);
	
	save_img($res_img, $imagedata['mime'], $path);
	if ($watermark==NULL){
		output_img($res_img, $imagedata['mime']);
		ImageDestroy($image);
		ImageDestroy($buf_img);
		ImageDestroy($res_img);
	} else {
		paste_watermark($path, $watermark);
	}
}


function not_resize($path, $watermark=NULL){
	if ($watermark==NULL){
		header("Last-Modified: ".gmdate("D, d M Y H:i:s", filemtime($path))." GMT");
		header("Content-type: image/jpeg");
		header("Content-Length: " . filesize($path));
		readfile($path);
		exit;
	} else {
		paste_watermark($path, $watermark);
	}
}



function display_default($dir) {
	$name = $dir."/design/img/no_image.jpg";
	$fp = fopen($name, 'rb');
	header("Last-Modified: ".gmdate("D, d M Y H:i:s", filemtime($name))." GMT");
	header("Content-Type: image/jpg");
	header("Content-Length: " . filesize($name));
	readfile($name);
	exit;
}

$_SERVER['QUERY_STRING'] = preg_replace("'%3Aw'si", ":w", $_SERVER['QUERY_STRING']);
$arr = explode(":", $_SERVER['QUERY_STRING']);

if (count($arr)>0) {
	$error = 0;
	$arr1 = explode(".", $arr[0]);
	if ($arr1[0] == 'i'){
		//Default values
		$id = 0;        //file's ID
		$h = 0;         //height of image
		$w = 0;         //width of iamge
		$const = 0;     //if we need constant size
		$pos = 'c';     //posision of croping (used only if $const == 1). Valid values: 'nw', 'n', 'ne', 'w', 'c', 'e', 'sw', 's', 'se'
		$force = false; //Used in watermark
		
		
		//parses all parameters
		$pairs = array();
		foreach($arr as $ar){
			if($pair == 'force')
				$force = true;
			$pair = explode(".",  $ar);
			$pairs[strtolower($pair[0])] = $pair[1];
		}

		if(array_key_exists('i', $pairs))
			$id = intval($pairs['i']);
		else
			$error = 1;
		if(array_key_exists('h', $pairs))
			$h = intval($pairs['h']);
		if(array_key_exists('w', $pairs))
			$w = intval($pairs['w']);
		if(array_key_exists('const', $pairs))
			$const = intval($pairs['const']);
		if(array_key_exists('pos', $pairs))
			$pos = $pairs['pos'];
		if(!in_array($pos, array('nw', 'n', 'ne', 'w', 'c', 'e', 'sw', 's', 'se')))
			$pos = 'c';
		if($w < 0 || $h < 0)
			$error = 1;
		//All parameters is preparsed

		//Get binary file
		$files = get_real_data($id, 'image');

		if ($files['link'] == NULL)
			display_default($setupdata['core_dir']);
		$info = $files;
		$files = $files['link'];
		
		$watermark = NULL;
		if (isset($setupdata['watermark']['name'])){
			$watermark['info']['height'] = $setupdata['watermark']['height'];
			$watermark['info']['width'] = $setupdata['watermark']['width'];
			$watermark['info']['name'] = $setupdata['watermark']['name'];
			$watermark['x'] = $setupdata['watermark']['x'];
			$watermark['y'] = $setupdata['watermark']['y'];
		}

		$scr = $setupdata['binary_path']."/".$files;
		if (!(file_exists($scr))) {
			$setupdata['binary_path'] = $setupdata['binary_path']."/".$info['parent'];
			$scr = $setupdata['binary_path']."/".$files;
		}

		if (strlen($scr) == 0 || !file_exists($scr) || is_dir($scr)){
			display_default($setupdata['core_dir']);
		}
		
		$t1 = explode("/", $scr);
		$t2 = explode("-", $t1[count($t1)-1]);
		list($s, $e) = explode(".", $t2[2]);
		$s = $setupdata['binary_path']."/".$t2[0]."-".$t2[1]."-";
	
		$imagedata = getimagesize($scr); 
		$image_original_width = $imagedata[0];
		$image_original_height = $imagedata[1];

		if($const != 1){//Calculates new image size
			if (($h == 0) or ($w == 0) or ($error == 1) or (!(isset($h))) or (!(isset($w))) or 
				(($h > $image_original_height) and ($w>$image_original_width))) {
				$h = $image_original_height;
				$w = $image_original_width;
			} else {
				$mult_x = $w / $image_original_width;        
				$mult_y = $h / $image_original_height;    
				if( $image_original_height * $mult_x < $h ){
					$new_width = $w;
					$new_height = $image_original_height * $mult_x;
				} else {
					$new_width = $image_original_width * $mult_y;
					$new_height = $h;
				}
				$h = round($new_height);
				$w = round($new_width);
			}
		}
		
		if (($watermark == NULL) || ($h < $watermark['info']['height']) || ($w < $watermark['info']['width']))
			$watermark = NULL;
		if($const == 1)
			$s .= $w."x".$h."_".$pos.".".$e;
		else			
			$s .= $w."x".$h.".".$e;

		if (isset($force) && ($force === true))
			$s .= "_force";
		
		if(is_file($s))//File is allready generated
			not_resize($s, $watermark);
		else if($const == 1)//We need constatn size file
			resize_const($scr, $w, $h, $pos, $s, $watermark);
		else//We need image with maximum allowed dimensions
			resize($scr, $w, $h, $s, $watermark);
	} else if ($arr1[0] == 'f'){
		$mysqlclass->connect_db($setupdata['HostName'], $setupdata['UserName'], $setupdata['Password'], $setupdata['DBName']);
		$id = $arr1[1];
		$info = $fileclass->file_info($id);
		$files = $fileclass->file_get_link($id);
		$file = $setupdata['binary_path']."/".$files;
		if (!(file_exists($file))) {
			$setupdata['binary_path'] = $setupdata['binary_path']."/".$info['parent'];
			$file = $setupdata['binary_path']."/".$files;
		}
		$t1 = explode("/", $file);
		$t2 = explode("-", $t1[count($t1)-1]);
		$name = $t2[count($t2)-1];
		if ((is_file($file)) and (strlen($file)>0)) {
			header('Content-type: '.$info['mime']);
			header('Content-Disposition: attachment; filename="'.$name.'"');
			header('Content-length: '.$info['size']);
			readfile($file);
		} 
		$mysqlclass->close_db();
	} else if ($arr1[0] == 's'){
		$mysqlclass->connect_db($setupdata['HostName'], $setupdata['UserName'], $setupdata['Password'], $setupdata['DBName']);
		$id = $arr1[1];
		$files = $imageclass->image_get_link($id, 'flash');
		$info = $files;
		$files = $files['link'];

		$file = $setupdata['binary_path']."/".$files;
		if (!(file_exists($file))) {
			$setupdata['binary_path'] = $setupdata['binary_path']."/".$info['parent'];
			$file = $setupdata['binary_path']."/".$files;
		}
		$t1 = explode("/", $file);
		$t2 = explode("-", $t1[count($t1)-1]);
		$name = $t2[count($t2)-1];
		if ((is_file($file)) and (strlen($file)>0)) {
//			header("Expires: Mon, 26 Jul 2004 05:00:00 GMT");
			header("Last-Modified: ".gmdate("D, d M Y H:i:s", filemtime($file))." GMT");
			header('Content-type: application/x-shockwave-flash');
			header('Content-length: '.$info['size']);
			readfile($file);
		}
		$mysqlclass->close_db();
	} else if ($arr1[0] == 'm'){
		$mysqlclass->connect_db($setupdata['HostName'], $setupdata['UserName'], $setupdata['Password'], $setupdata['DBName']);
		$id = $arr1[1];
		if (count($arr) == 4){
			$arr1 = explode(".",  $arr[1]);
			if (($arr1[0] <> 'w') and ($arr1[0] <> 'h')) $error = 1;
			else {
				if ($arr1[0] == 'w') $w = $arr1[1];
				else if ($arr1[0] == 'h') $h = $arr1[1];
			}
			$arr1 = explode(".",  $arr[2]);
			if (($arr1[0] <> 'w') and ($arr1[0] <> 'h')) $error = 1;
			else {
				if ($arr1[0] == 'w') $w = $arr1[1];
				else if ($arr1[0] == 'h') $h = $arr1[1];
			}
			$arr1 = explode(".",  $arr[3]);
			if ($arr1[0] <> 'page') display_default($setupdata['core_dir']);
			else $page_id = $arr1[1];
		} elseif (count($arr) == 2){
			$arr1 = explode(".",  $arr[1]);
			if ($arr1[0] <> 'page') display_default($setupdata['core_dir']);
			else {
				$h = 0; $w = 0;
				$page_id = $arr1[1];
			}
		} else {
			display_default($setupdata['core_dir']);
		}
		
		$files = $imageclass->image_get_link($id, 'imagew');
		if ($files['link'] == NULL) display_default($setupdata['core_dir']);
		$info = $files;
		$files = $files['link'];

		include $setupdata['core_dir']."/modules/watermark/watermarkclass.php";
		$watermarkclass = new watermarkclass;
		$watermark = $watermarkclass->get_watermark_data_by_page_id($page_id);
		
		if (($files == NULL) || ($watermark == NULL)) display_default($setupdata['core_dir']);
		$scr = $setupdata['binary_path']."/".$files;
		if (!(file_exists($scr))) {
			$setupdata['binary_path'] = $setupdata['binary_path']."/".$info['parent'];
			$scr = $setupdata['binary_path']."/".$files;
		}

		if (!file_exists($scr) || is_dir($scr)){
			display_default($setupdata['core_dir']);
		}
	
		if (strlen($scr) == 0) display_default($setupdata['core_dir']);
		
		$t1 = explode("/", $scr);
		$t2 = explode("-", $t1[count($t1)-1]);
		list($s, $e) = explode(".", $t2[2]);
		$s = $setupdata['binary_path']."/".$t2[0]."-".$t2[1]."-";

		$imagedata = getimagesize($scr); 
		$image_original_width = $imagedata[0];
		$image_original_height = $imagedata[1];

		if (($h == 0) or ($w == 0) or ($error == 1) or (!(isset($h))) or (!(isset($w))) or 
			(($h > $image_original_height) and ($w>$image_original_width))) {
			$h = $image_original_height;
			$w = $image_original_width;
		} else {
			$mult_x = $w / $image_original_width;        
			$mult_y = $h / $image_original_height;    
			if( $image_original_height * $mult_x < $h ){
				$new_width = $w;
				$new_height = $image_original_height * $mult_x;
			} else {
				$new_width = $image_original_width * $mult_y;
				$new_height = $h;
			}
			$h = round($new_height);
			$w = round($new_width);
		}

		if (($watermark == NULL) || ($h < $watermark['info']['height']) || ($w < $watermark['info']['width'])){
			$watermark = NULL;
		}

		$s .= $w."x".$h.".".$e;
		if (!(is_file($s))) resize($scr, $w, $h, $s, $watermark);
		else not_resize($s, $watermark);
		$mysqlclass->close_db();
	} else if ($arr1[0] == 'c'){
		session_name("tvs_session_id");
		session_start();
		include $setupdata['core_dir']."/classes/captcha.php";
		$captcha = new CaptchaClass(4);
		$captcha->SetFont($setupdata['core_dir']."/fonts/arial.ttf");
		$captcha->SetFontDir($setupdata['core_dir']."/fonts/");
		$captcha->display();
		$_SESSION['captcha'] = $captcha->getString("1");
	} else if ($arr1[0] == 'd'){
		session_name("tvs_session_id");
		session_start();
		include $setupdata['core_dir']."/classes/captcha.php";
		$captcha = new CaptchaClass(6);
		$captcha->SetFont($setupdata['core_dir']."/fonts/arial.ttf");
		$captcha->SetFontDir($setupdata['core_dir']."/fonts/");
		$captcha->display(1);
		$_SESSION['captcha'] = $captcha->getString("2");
	} else {
		//die();
	}
}
die();
?>
